<?php
namespace app\api\controller;
use think\Controller;
use think\Db;
use think\Validate;
use think\Config;

class Bargain extends Controller{
    //好友砍价
    //砍价商品列表
    public function bargainGoodsList(){
       $page = input('post.page');
       if($page){if(!is_numeric($page)){return json_encode(['code'=>401,'msg'=>'page参数类型错误']);}}else{$page = 0;}
       $goods_list = db('goods_bargain')->field('bargain_id,goods_id,spec_item,min_price,start_time,end_time')
                                        ->where("state = 1")
                                        ->order('bargain_id desc')
                                        ->limit($page*5,5)
                                        ->select();
       foreach($goods_list as $key=>$value){
          //activity_status 0 表示活动未开始;1进行中;2已结束;
          if(time() < $value['start_time']){
               $goods_list[$key]['activity_status'] = 0;
           }elseif(time() > $value['end_time']){
               $goods_list[$key]['activity_status'] = 2;
           }else{
               $goods_list[$key]['activity_status'] = 1;
           }
           $goods_info = db('goods')->field('name as goods_name,mode,thumbnail_img')->where("goods_id = {$value['goods_id']}")->find();
           $goods_list[$key]['goods_name'] = $goods_info['goods_name'];
           $goods_list[$key]['mode'] = $goods_info['mode'];//0一口价;1多规格;
           if(!Validate::is($goods_info['thumbnail_img'],'url')){
               $goods_list[$key]['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$goods_info['thumbnail_img'];
           }
           $map = "goods_id = {$value['goods_id']} AND price_key = {$value['spec_item']}";
           $spec_info = db('spec_goods_price')->field('store,price')->where($map)->find();
           $goods_list[$key]['store'] = $spec_info['store'];//商品库存;
           $goods_list[$key]['goods_price'] = $spec_info['price'];//商品价格;
           if($value['spec_item'] != 0){
              $goods_list[$key]['spec_name'] = db('spec_item')->where("item_id = {$value['spec_item']}")->value('spec_item');//规格名称;
           }
           $goods_list[$key]['goods_type'] = 2;//2砍价;  
       }
       if($goods_list){
          return json_encode(['code'=>200,'msg'=>'请求成功','goods_list'=>$goods_list]);
       }else{
          return json_encode(['code'=>201,'msg'=>'暂无数据']);
       }
    }

    //提交订单
    public function submitOrder(){
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){return json_encode(array('code'=>401,'msg'=>'user_id类型错误'));}
        $user_info = db('user')->field('openid,frozen_integral,available_integral')->where("user_id = {$user_id}")->find();
        $openid = $user_info['openid'];
        $store_id = input('post.store_id');
        if(!is_numeric($store_id)){return json_encode(array('code'=>401,'msg'=>'store_id类型错误'));}
        $order_type = input('post.order_type');//1快递;2自提
        if(!is_numeric($order_type)){return json_encode(array('code'=>401,'msg'=>'order_type类型错误'));}
        $type = input('post.type');//1在售;2共享;
        $goods_type = input('post.goods_type');//1秒杀;2砍价;
        $data = array(
           'user_id' => $user_id,
           'store_id' => $store_id,
           'order_type' => $order_type
          );
        if($data['order_type'] == 1){
               $name = input('post.name');
               if($name == '' || $name == 'undefined' || $name == 'null'){return json_encode(array('code'=>401,'msg'=>'请选择有效的收货人姓名'));}
               $data['name'] = $name;
               $phone = input('post.phone');
               if($phone =='' || $phone == 'undefined' || $phone == 'null'){return json_encode(array('code'=>401,'msg'=>'请填写有效的手机号'));}
               $data['phone'] = $phone;
               $consignee = input('post.consignee');
               if($consignee == '' || $consignee == 'undefinde' || $consignee == 'null'){return json_encode(array('code'=>401,'msg'=>'请填写有效的收货人地址'));}
               $data['consignee'] = $consignee;
        }
        if($goods_type == 1){
             $seckill_price = input('post.seckill_price');
             if($seckill_price == '' || $seckill_price == 'undefined' || $seckill_price == 'null'){
                return json_encode(['code'=>401,'msg'=>'请填写秒杀商品价格']);
             }
             $seckill_id = input('post.seckill_id');
             if(!is_numeric($seckill_id)){return json_encode(['code'=>401,'msg'=>'seckill_id类型错误']);}
             $seckill_info = db('goods_seckill')->field('price,limits')->where("seckill_id = {$seckill_id}")->find();
             if($seckill_price != $seckill_info['price']){return json_encode(['code'=>401,'msg'=>'商品秒杀价格被篡改']);}
             $data['order_goods_type'] = 1;
             $successKillData = [];
             $successKillData['seckill_id'] = $seckill_id;
             $successKillData['user_id'] = $user_id;
             $successKillData['create_time'] = time();
             $successKillData['state'] = 0;
        }elseif($goods_type == 2){
             $data['order_goods_type'] = 2;
             $bargain_id = input('post.bargain_id');
             if(!is_numeric($bargain_id)){return json_encode(['code'=>401,'msg'=>'bargain_id类型错误']);}
             $bargainProgressData = [];
             $bargainProgressData['bargain_id'] = $bargain_id;
             $bargainProgressData['user_id'] = $user_id;
             $bargainProgressData['bargain_count'] = 0;
             $bargainProgressData['create_time'] = time(); 
        }
        $goods_price_sum = input('post.goods_price_sum');
        if($goods_price_sum == '' || $goods_price_sum == 'undefined' || $goods_price_sum == 'null'){
           return json_encode(array('code'=>401,'msg'=>'请填写订单金额'));
        }
        $data['goods_price'] = $goods_price_sum;//订单金额  
        $pay_price = input('post.pay_price');
        if($pay_price == '' || $pay_price == 'undefined' || $pay_price == 'null'){
            return json_encode(['code'=>401,'msg'=>'实际支付金额缺失']);
        }
        $data['pay_price'] = $pay_price;//实际支付金额;
        $data['order_sn'] = 'B'.generateOrderNum();
        $data['type'] = 2;
        $data['add_time'] = time();
        $mode = input('post.mode');
        $goods = json_decode(input('post.goods'),true);
        $goods_name = [];
        foreach($goods as $key=>$value){
              //求商品名
              $goods_list_name = db('goods')->where("goods_id = {$value['goods_id']}")->value('name');
              $goods_name[] = $goods_list_name.'*'.$value['goods_number'];
              $field = 'store,price';
              $goods_info = db('spec_goods_price')->field($field)->where("goods_id = {$value['goods_id']} AND price_key = {$value['spec_item']}")->find();
              $goods[$key]['goods_real_price'] = $goods_info['price'];
              $goods[$key]['goods_real_store'] = $goods_info['store'];
        }
        $goods_name = implode(',',$goods_name);
        $price = [];
        foreach($goods as $k=>$v){
              if($goods[$k]['goods_real_price'] != $goods[$k]['goods_price']){
                      return json_encode(array('code'=>401,'msg'=>'goods_price参数被篡改'));
              }
              unset($goods[$k]['goods_real_price']);
              if($goods[$k]['goods_number'] > $goods[$k]['goods_real_store']){
                  return json_encode(array('code'=>401,'msg'=>'库存不足,请重新进行选择'));
              }
              unset($goods[$k]['goods_real_store']);
              if($goods_type == 1){
                 if($goods[$k]['goods_number'] > $seckill_info['limits']){
                     return json_encode(['code'=>401,'msg'=>'您购买该商品的数量已超过本次活动限制！']);
                 }
                 $price[] = $seckill_price*$goods[$k]['goods_number'];
              }elseif($goods_type == 2){
                 $price[] = $goods[$k]['goods_price']*$goods[$k]['goods_number'];
              }
              
        }
        //$data['type']  1共享  2在线销售
        if($data['type'] == 2){
           $goods_name = '购买珠宝（'.$goods_name.'）'; 
           $price_sum = array_sum($price);
           $real_goods_price = $price_sum;  
           if($price_sum != $goods_price_sum){return json_encode(array('code'=>401,'msg'=>'订单总价不对'));}    
        }
        $real_pay_price = $real_goods_price;//   
        if($real_pay_price != $data['pay_price']){return json_encode(['code'=>401,'msg'=>'实际支付金额不对']);}
        //$data['type'] 为1表示共享珠宝;$data['type']为2表示在线销售;  
        Db::startTrans();
        try{ 
                $order_id = db('order')->insertGetId($data);
                foreach($goods as $k=>$vo){
                    $goods[$k]['order_id'] = $order_id;
                }
                $add_goods = db('order_goods')->insertAll($goods);
                $goods_info = db('order_goods')->field('order_goods_id,goods_id,spec_item,goods_number')->where("order_id = {$order_id}")->select();
                foreach($goods_info as $k=>$vo){
                    $where = "goods_id = {$vo['goods_id']} AND price_key = {$vo['spec_item']}";
                    db('spec_goods_price')->where($where)->setDec('store',$vo['goods_number']);
                    $price_id = db('spec_goods_price')->where($where)->value('price_id');
                    $code = [];
                    for($i=0;$i<$vo['goods_number'];$i++){
                        $code_id = db('code')->field('code_id')->where("price_id = {$price_id} AND state = 0")->order('code_id')->find();
                        $update_data = array('state'=>1,'update_time'=>time(),'sale_type'=>1);
                        db('code')->where("code_id = {$code_id['code_id']}")->update($update_data);
                        $code[] = $code_id['code_id'];
                    }
                    $code = implode(',',$code);
                    db('order_goods')->where("order_goods_id = {$vo['order_goods_id']}")->update(['code'=>$code]);
                }
                $logData = [];
                $logData['order_id'] = $order_id;
                $logData['u_id'] = $user_id;
                $logData['content'] = '用户下单';
                $logData['create_time'] = time();
                db('order_log')->insert($logData);
                if($goods_type == 1){
                    $successKillData['order_id'] = $order_id;
                    db('goods_success_killed')->insert($successKillData);
                    if($data['pay_price'] > 0){
                        // 实例支付接口
                        $pay = & load_wechat('Pay');
                        // 获取预支付ID
                        $notify_url = 'https://'.$_SERVER['HTTP_HOST'].'/api/Bargain/notify';
                        // $data['pay_price'] = 0.01;
                        $prepayid = $pay->getPrepayId($openid,$goods_name, $data['order_sn'], $data['pay_price'] * 100, $notify_url, $trade_type = "JSAPI");
                        // dump($prepayid);die;

                        // 创建JSAPI签名参数包
                        $options = $pay->createMchPay($prepayid);
                    }
                }elseif($goods_type == 2){
                    $bargainProgressData['order_id'] = $order_id;
                    $bargainProgressData['deal_money'] = $data['pay_price'];
                    db('goods_bargain_progress')->insert($bargainProgressData);
                }
                Db::commit();
        } catch (\Exception $e){
                Db::rollback();
                return json_encode(['code' => 201,'msg' => '订单提交失败']);
        }
        if($goods_type == 1){
           return json_encode(['code' => 200,'msg' => '提交成功','pay' => $options,'order_id' => $order_id]);
        }elseif($goods_type == 2){
           return json_encode(['code' => 200,'msg' => '提交成功','order_id' => $order_id]);
        }
   } 

   //砍价商品支付
   public function bargainGoodsPay(){
       $order_id = input('post.order_id');
       if(!is_numeric($order_id)){return json_encode(['code'=>401,'msg'=>'order_id类型错误']);}
       $order_info = db('order')->field('order_sn,user_id,pay_price')->where("order_id = {$order_id}")->find();
       $openid = db('user')->where("user_id = {$order_info['user_id']}")->value('openid');
       $goods_name = [];
       $goods_info = db('order_goods')->field('goods_id,goods_number')->where("order_id = {$order_id}")->select();
       foreach($goods_info as $key=>$value){
          //求商品名
          $bargain_goods_name = db('goods')->where("goods_id = {$value['goods_id']}")->value('name');
          $goods_name[] = $bargain_goods_name.'*'.$value['goods_number'];
       }
       $goods_name = '购买珠宝（'.implode(',',$goods_name).'）'; 
       if($order_info['pay_price'] > 0){
          // 实例支付接口
          $pay = & load_wechat('Pay');
          // 获取预支付ID
          $notify_url = 'https://'.$_SERVER['HTTP_HOST'].'/api/Bargain/notify';
          // $data['pay_price'] = 0.01;
          $prepayid = $pay->getPrepayId($openid,$goods_name, $order_info['order_sn'], $order_info['pay_price'] * 100, $notify_url, $trade_type = "JSAPI");
          // dump($prepayid);die;

          // 创建JSAPI签名参数包
          $options = $pay->createMchPay($prepayid);
       }
       if($options){
           return json_encode(['code' => 200,'msg' => '提交成功','pay' => $options]); 
       }else{
           return json_encode(['code'=>201,'msg'=>'提交失败']);
       }

   }

   //回调
   public function notify(){
        // 实例支付接口
        $pay = & load_wechat('Pay');

        // 获取支付通知
        $notifyInfo = $pay->getNotify();

        // 支付通知数据获取失败
        if($notifyInfo===FALSE){
            // 接口失败的处理
            echo $pay->errMsg;
        }else{
            //支付通知数据获取成功
             if ($notifyInfo['result_code'] == 'SUCCESS' && $notifyInfo['return_code'] == 'SUCCESS') {
                $order = db('order')->where("order_sn = '{$notifyInfo['out_trade_no']}'")->find();
                if($order['order_status'] > 0){
                    return FALSE;
                }
                Db::startTrans();
                try{
                    $data = [];
                    $data['order_status'] = 1;
                    $data['pay_time'] = time();
                    db('order') -> where("order_sn = '{$notifyInfo['out_trade_no']}'") -> update($data);
                    if($order['order_goods_type'] == 1){
                       db('goods_success_killed')->where("order_id = {$order['order_id']}")->update(['state'=>1]);
                    }
                    $addData = [];
                    $addData['order_id'] = $order['order_id'];
                    if($order['type'] == 1){$addData['type'] = 1;}
                    $addData['pay_code'] = $notifyInfo['transaction_id'];
                    $addData['pay_price'] = $notifyInfo['total_fee']/100;
                    $addData['time'] = strtotime($notifyInfo['time_end']);
                    $addData['notify_info'] = json_encode($notifyInfo);
                    db('order_pay')->insert($addData);
                    $logData = [];
                    $logData['order_id'] = $order['order_id'];
                    $logData['u_id'] = $order['user_id'];
                    $logData['content'] = '用户支付。支付方式:微信支付;交易流水号:'.$notifyInfo['transaction_id'].';交易金额:￥'.$addData['pay_price'].'。';
                    $logData['create_time'] = time();
                    db('order_log')->insert($logData);
                    Db::commit();
                 } catch (\Exception $e) {
                    Db::rollback();
                 }
                 $pay->replyXml(['return_code' => 'SUCCESS', 'return_msg' => 'DEAL WITH SUCCESS']);
             }
        }
   }

   //砍价页面 订单详情
   public function orderDetail(){
        $order_id = input('post.order_id');
        if(!is_numeric($order_id)){return json_encode(['code'=>401,'msg'=>'order_id类型错误']);}
        $map = "order_id = {$order_id}";
        $order_info = db('order')->field('user_id,pay_price')
                                 ->where($map)
                                 ->find();
        //用户信息
        $user_info = db('user')->field('name,img')->where("user_id = {$order_info['user_id']}")->find();
        $order_info['user_name'] = $user_info['name'];
        $order_info['user_img'] = $user_info['img'];
        //订单商品信息
        $order_goods_info = db('order_goods')->field('goods_id,spec_item,spec_item_key,goods_number,goods_price')
                                             ->where($map)
                                             ->find();
        $goods_info = db('goods')->field('name as goods_name,thumbnail_img')
                                 ->where("goods_id = {$order_goods_info['goods_id']}")
                                 ->find();
        $order_goods_info['goods_name'] = $goods_info['goods_name'];
        if(!Validate::is($goods_info['thumbnail_img'],'url')){
            $order_goods_info['thumbnail_img'] = 'https://'.Config::get('oss.bucket').'.'.Config::get('oss.endpoint').$goods_info['thumbnail_img'];
        }
        $order_info['goods'] = $order_goods_info;
        $bargain_info = db('goods_bargain_progress')->field('progress_id,bargain_id,deal_money')
                                                    ->where($map)
                                                    ->find();
        $bargain_goods_info = db('goods_bargain')->field('max_price,min_price,end_time')
                                                 ->where("bargain_id = {$bargain_info['bargain_id']}")
                                                 ->find();
        $order_info['goods']['min_price'] = $bargain_goods_info['min_price'];//最低价
        $order_info['end_time'] = date("Y-m-d H:i:s",$bargain_goods_info['end_time']);//结束时间
        //砍价记录
        $order_info['bargain_record'] = db('goods_bargain_list')->field('assistor_id,create_time,bargain_money')
                                                                ->where("progress_id = {$bargain_info['progress_id']}")
                                                                ->select();
        foreach($order_info['bargain_record'] as $key=>$value){
           $order_info['bargain_record'][$key]['create_time'] = date("Y-m-d H:i",$value['create_time']);
           $$record_user_info = db('user')->field('name,img')->where("user_id = {$value['assistor_id']}")->find();
           $order_info['bargain_record'][$key]['record_user_name'] = $record_user_info['name'];
           $order_info['bargain_record'][$key]['record_img'] = $record_user_info['img'];
        }
        $order_info['bargain_money'] = $order_info['goods']['goods_price'] - $order_info['pay_price'];//已砍金额;
        $order_info['bargain_remaining'] = $order_info['pay_price'] - $order_info['goods']['min_price'];//还可砍金额;
        //当前交易价格等于最低价,此时商品价格只能为最低价
        if($order_info['pay_price'] == $order_info['goods']['min_price']){
            $order_info['bargain_status'] = 1;
        }else{
            $order_info['bargain_status'] = 0;//bargain_status 0可以继续砍价;1不可以继续砍价;
        }
        return json_encode(['code'=>200,'msg'=>'请求成功','order_info'=>$order_info]);
   }

   //执行砍价
   public function bargaining(){
        $order_id = input('post.order_id');
        if(!is_numeric($order_id)){return json_encode(['code'=>401,'msg'=>'order_id类型错误']);}
        $user_id = input('post.user_id');
        if(!is_numeric($user_id)){return json_encode(['code'=>401,'msg'=>'user_id类型错误']);}
        $map = "order_id = {$order_id}";
        $order_info = db('order')->field('order_status,pay_price')
                                 ->where()
                                 ->find();
        if($order_info['order_status'] != 0){return json_encode(['code'=>401,'msg'=>'订单状态错误']);}
        $bargain_progress_info = db('goods_bargain_progress')->field('progress_id,bargain_id')
                                                             ->where($map)
                                                             ->find();
        $bargain_user = db('goods_bargain_list')->where("progress_id = {$bargain_progress_info['progress_id']} AND assistor_id = {$user_id}")->find();
        if($bargain_user){return json_encode(['code'=>401,'msg'=>'用户已参加过砍价活动,请勿重复砍价']);}
        //获取当前订单商品价格,最低价
        $order_goods_info = db('order_goods')->field('goods_id,spec_item,spec_item_key,goods_number,goods_price')
                                             ->where($map)
                                             ->find();
        $bargain_goods_info = db('goods_bargain')->field('max_price,min_price,end_time,join_count')
                                                 ->where("bargain_id = {$bargain_info['bargain_id']}")
                                                 ->find();
        if($order_info['pay_price'] == $bargain_goods_info['min_price']){
            return json_encode(['code'=>401,'msg'=>'该商品已被砍至最低价']);
        }
        //砍价的随机算法   pay_price 当前订单需要支付的金额  goods_price商品价格  goods_price - pay_price - rand_price > 0 ? rand_price :goods_price - pay_price;
        $rand_price = rand(0,(int) $bargain_goods_info['max_price']);
        $bargainListData = [];
        $bargainListData['progress_id'] = $bargain_progress_info['progress_id'];
        $bargainListData['assistor_id'] = $user_id;
        $bargainListData['create_time'] = time();
        $bargainListData['bargain_money'] = $order_goods_info['goods_price'] - $order_info['pay_price'] > $rand_price?$rand_price:($order_goods_info['goods_price'] - $order_info['pay_price']);
        Db::startTrans();
        try{
           db('goods_bargain_progress')->where($map)->setInc('bargain_count');
           db('goods_bargain_progress')->where($map)->setDec('deal_money',$bargainListData['bargain_money']);
           db('order')->where($map)->setDec('pay_price',$bargainListData['bargain_money']);
           db('goods_bargain_list')->insert($bargainListData);
        }catch(\Exception $e){
           Db::rollback();
           return json_encode(['code'=>201,'msg'=>'砍价失败']);
        }
        return json_encode(['code'=>200,'msg'=>'砍价成功']);
   }
}